<template>
  <div class="main">
    <div class="video-main">
      <!-- 简介 -->
      <div class="video-info">
        <div class="video-title">
          <el-tooltip :content="video.videoTitle">
            <span>{{ video.videoTitle }}</span></el-tooltip>
        </div>
        <div class="video-detail">
          <i class="el-icon-video-play"></i>
          <span>{{ video.videoPlay }}</span>
          <i class="el-icon-chat-dot-round"></i>
          <span>{{ video.videoType }}</span>
          <i class="el-icon-date"></i>
          <time>{{ formatTimeAgo(video.createTime) }}</time>
        </div>
      </div>

      <!-- 关注 -->
      <div class="video-up">
        <div class="up-cover">
          <el-image class="cover-img" :src="downloadUrl + userInfo.userCover" lazy
            @click="$router.push('/c/user/userCenter?userId=' + video.userId)"></el-image>
        </div>
        <div class="up-info">
          <div class="up-nickname">
            <span>{{ userInfo.nickName }}</span>
          </div>
          <div class="up-introduction">
            <span v-if="userInfo.userIntroduction">{{ userInfo.userIntroduction }}</span>
            <span v-else>该用户还没有简介哦~</span>
          </div>
          <div class="up-concern">
            <el-button v-if="userInfo.hasFollow" @click="deleteUserFollow()" type="primary">已关注</el-button>
            <el-button v-else @click="addUserFollow()">加关注</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 视频 -->
    <div class="video-video">
      <div class='demo'>
        <div class="custom-progress-bar">
          <!-- 在这里添加你自定义的进度条组件或样式 -->
        </div>
        <videoDplay2 class="player" :url="videoUrl" :pic="videoPic" v-if="lock">
        </videoDplay2>
      </div>

      <div class="video-button">
        <el-button v-if="video.hasCollection" @click="deleteUserCollection()" type="primary">
          <i class="el-icon-star-on"></i>已收藏</el-button>
        <el-button v-else @click="addUserCollection()">
          <i class="el-icon-star-off"></i>收藏</el-button>
        <el-button @click="">
          <i class="el-icon-share"></i>分享</el-button>
      </div>
      <!-- <el-dialog title="添加到文件夹" :visible.sync="showForm" width="30%">
        <div>
          <el-radio v-for="tab in collection" :key="tab.id" v-model="" :label="tab.id"
            :name="tab.collectionName">{{ tab.collectionName }}</el-radio>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showForm = false">取消</el-button>
          <el-button type="primary" @click="addFavorites">确定</el-button>
        </div>
      </el-dialog> -->
      <div style="width: 65%;">
        <el-divider></el-divider>
      </div>
      <div class="video-Introduction">
        {{ video.videoIntroduction }}
      </div>
    </div>

    <!--    评论  -->
    <div class="video-comment">
      <div class="comment-top">
        <div class="comment-top-count">评论 {{ totalComments }}</div>
        <div class="comment-top-send">
          <div style="width: 80px; text-align: center;">
            <img class="comment-top-cover" :src="downloadUrl + userInfo.userCover" />
          </div>
          <div style="flex: 1;">
            <el-input v-model="commentForm.content" type="textarea" placeholder="只是一直在等你而已，才不想被评论呢~"></el-input>
          </div>
          <el-button class="comment-top-sendbutton" type="primary" @click="saveComment()">发布</el-button>
        </div>
      </div>

      <!--  评论列表  -->
      <div style="width: 750px; text-align: left; margin-top: 10px">
        <div v-for="item in comments" :key="item.id" style="border-bottom: 1px solid #ccc; padding: 10px 0; ">
          <div style="display: flex">
            <!--  头像  item.avatarUrl-->
            <div style="width: 100px; text-align: center">
              <el-image :src="item.id" style="width: 50px; height: 50px;cursor: pointer; border-radius: 50%"></el-image>
            </div>
            <!--  中间  -->
            <div style="flex: 1; font-size: 12px; font-family: SimHei, Arial, sans-serif;
                      font-weight: 500;padding: 5px 0; line-height: 25px;">
              <b style="cursor: pointer; font-family: SimHei, Arial, sans-serif;">{{ item.nickname }}</b>
              <!--  评论内容  -->
              <span style="display: block; font-family: SimHei, Arial, sans-serif; font-size: 16px; line-height: 24px;">
                {{ item.comment }}</span>
              <!--  评论时间  -->
              <div style="display: flex; line-height: 20px; margin-top: 5px; align-items: center; color: #969aa1">
                <div style="width: fit-content;">
                  <i class="el-icon-time"></i><span style="margin-left: 5px;">{{ formatTimeAgo(item.createTime) }}</span>
                </div>
                <div style="flex: 1; line-height: 20px; margin-left: 10px" class="button-reply ">
                  <el-button class="comment-button" style="margin-left: 5px; color: #969aa1;" type="text"
                    @click="handleReply(item.id)">回复</el-button>
                  <el-button type="text" style="color: red;" @click="deleteComment(item.id)"
                    v-if="userInfo.id === item.userId">删除</el-button>
                </div>
              </div>
            </div>
          </div>

          <!--  评论数量不超过三条显示的二级评论  -->
          <div v-if="item.children.length > 3">
            <!--  二级评论  -->
            <div v-if="item.children.length" style="padding-left: 90px;" class="comment-content1">
              <!-- 添加一个状态变量来切换显示/隐藏多余的评论  -->
              <div
                v-for="(subComment, subCommentIndex) in item.children.slice(0, item.showAllComments ? item.children.length : 3)"
                :key="subComment.id" v-show="!collapsedComments[item.id]"
                style="border-bottom: 1px solid #fff;;border-radius: 6px; ">
                <!-- 回复列表 -->
                <div style="font-size: 14px; padding: 5px 0; line-height: 25px; border-width: 10px;">
                  <!-- 回复的@ -->
                  <!-- 图片，人名，回复内容 -->
                  <div style="padding-left: 5px; font-size: 16px;">
                    <el-image :src="subComment.avatarUrl"
                      style="width: 30px; cursor: pointer; height: 30px;top: 8px; border-radius: 50%"></el-image>
                    <b
                      style="margin-left: 8px; font-size: 14px; cursor: pointer; font-family: SimHei, Arial, sans-serif; ">{{
                        subComment.nickname }}</b>
                    <a v-if="subComment.pnickname !== item.nickname" class="comment-a"> <b style="color: #222222">回复</b>
                      @{{ subComment.pnickname }}:</a>
                    <a v-else></a>
                    <span
                      style="color: #666666; font-family: SimHei, Arial, sans-serif; font-weight:400; font-size: 14px;">
                      {{ subComment.content }}</span>
                  </div>

                  <div style="display: flex; line-height: 20px; margin-top: 5px; align-items: center; color: #969aa1">
                    <div style="width: fit-content;">
                      <i class="el-icon-time"></i>
                      <span style="margin-left: 5px;">{{ formatTimeAgo(subComment.time) }}</span>
                    </div>
                    <div style="flex: 1; line-height: 20px; margin-left: 10px">
                      <el-button style="margin-left: 5px; color: #969aa1" type="text" @click="handleReply(subComment.id)">
                        回复</el-button>
                      <el-button type="text" style="color: red" @click="del(subComment.id)"
                        v-if="userInfo.id === subComment.userId">
                        删除</el-button>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 显示/隐藏二级评论的按钮 -->
              <div>
                <!-- 添加一个按钮或其他元素来切换显示/隐藏多余的评论 -->
                <el-button type="text" v-bind:item="item" v-on:click="toggleComments(item)" style="color: #8c939d">
                  <span v-if="!item.showAllComments">共{{ secondaryCommentsCount[item.id] }}条回复,</span>
                  {{ item.showAllComments ? '收起评论' : '点击查看' }}
                </el-button>
              </div>
            </div>
          </div>

          <!--        评论数量超过三条显示的二级评论-->
          <div v-else>
            <!--   二级评论-->
            <div v-if="item.children.length" style="padding-left: 90px;" class="comment-content1">
              <!-- 添加一个状态变量来切换显示/隐藏多余的评论 -->
              <div
                v-for="(subComment, subCommentIndex) in item.children.slice(0, item.showAllComments ? item.children.length : 3)"
                :key="subComment.id" v-show="!collapsedComments[item.id]"
                style="border-bottom: 1px; solid: #fff; border-radius: 6px;">
                <!-- 回复列表 -->
                <div style="font-size: 14px; padding: 5px 0; line-height: 25px; border-width: 10px;">
                  <!-- 回复的@ -->
                  <!-- 图片，人名，回复内容 -->
                  <div style="padding-left: 5px; font-size: 16px;">
                    <el-image :src="subComment.avatarUrl"
                      style="width: 30px; cursor: pointer; height: 30px; top: 8px; border-radius: 50%"></el-image>
                    <b
                      style="margin-left: 8px; font-size: 14px; cursor: pointer; font-family: SimHei, Arial, sans-serif;">
                      {{ subComment.nickname }}</b>
                    <a v-if="subComment.pnickname !== item.nickname" class="comment-a">
                      <b style="color: #222222">回复</b> @{{ subComment.pnickname }}:</a>
                    <a v-else></a>
                    <span
                      style="color: #666666; font-family: SimHei, Arial, sans-serif; font-weight:400; font-size: 14px;">
                      {{ subComment.content }}</span>
                  </div>

                  <div style="display: flex; line-height: 20px; margin-top: 5px; align-items: center; color: #969aa1">
                    <div style="width:fit-content;">
                      <i class="el-icon-time"></i>
                      <span style="margin-left: 5px;">{{ formatTimeAgo(subComment.time) }}</span>
                    </div>
                    <div style="flex: 1; line-height: 20px; margin-left: 10px; font-size: 16px">
                      <el-button class="comment-button" style="margin-left: 5px; color: #969aa1" type="text"
                        @click="handleReply(subComment.id)">回复</el-button>
                      <el-button type="text" style="color: red" @click="del(subComment.id)"
                        v-if="userInfo.id === subComment.userId">删除</el-button>
                    </div>
                  </div>
                </div>
              </div>

            </div>
          </div>
        </div>
      </div>

      <el-dialog title="回复" :visible.sync="dialogFormVisible" width="50%">
        <el-form label-width="80px" size="small">
          <el-form-item label="回复内容">
            <el-input type="textarea" v-model="commentForm.contentReply" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false" size="small">取 消</el-button>
          <el-button type="primary" @click="saveComment()" size="small">确 定</el-button>
        </div>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import { getVideoDetail } from "@/api/video/video";
import { getUserDetail } from "@/api/user/user";
import { addUserFollow, deleteUserFollow } from "@/api/user/userFollow";
import { addUserCollection, deleteUserCollection } from "@/api/user/userCollection";

import videoDplay2 from "@/views/video/videoDplay2"

export default {
  name: "VideoDetail",
  components: {
    videoDplay2
  },
  data() {
    return {
      thisUserId: this.$store.getters.userInfo.id,
      video: {},
      userInfo: {},

      comments: [
        {
          "id": "1",
          "nickname": "大声发",
          "comment": "这是一条评论",
          "createTime": "2023-12-12",
          "userId": "1",
          children: {
            "length": "",
          }
        },
      ],
      commentList: [],
      commentForm: {},
      collapsedComments: {},
      dialogFormVisible: false,

      downloadUrl: process.env.VUE_APP_DOWNLOAD_URL,
      downloadVideoUrl: process.env.VUE_APP_DOWNVIDEO_URL,
      videoUrl: '',
      videoPic: '',
      lock: false,
    }
  },
  computed: {
    /*评论数*/
    totalComments() {
      let count = 0;
      this.comments.forEach(item => {
        count += 1; // 加上当前一级评论
        count += item.children.length; // 加上当前一级评论的二级评论数量
      });
      return count;
    },
    /*每个一级评论下二级评论的数量*/
    secondaryCommentsCount() {
      const counts = {};
      this.comments.forEach((item) => {
        counts[item.id] = item.children.length;
      });
      return counts;
    }
  },

  created() {
    this.getVideoDetail();
    // this.loadComment();
  },

  methods: {
    getVideoDetail() {
      getVideoDetail(this.$route.params.id).then((res) => {
        if (res.data.data) {
          this.video = res.data.data;
          this.videoUrl = this.downloadVideoUrl + res.data.data.videoUrl;
          this.videoPic = this.downloadUrl + res.data.data.videoCover;
          this.lock = true;
          this.getUserDetail();
        }
      });
    },
    getUserDetail() {
      getUserDetail(this.video.userId).then((res) => {
        if (res.data.data) {
          this.userInfo = res.data.data;
        }
        console.log();
      });
    },
    // 关注接口
    addUserFollow() {
      let fans = {
        "userId": this.thisUserId,
        "followId": this.video.userId,
      }
      addUserFollow(fans).then((res) => {
        this.getUserDetail();
      });
    },
    deleteUserFollow() {
      let fans = {
        "userId": this.thisUserId,
        "followId": this.video.userId,
      }
      deleteUserFollow(fans).then((res) => {
        this.getUserDetail();
      });
    },
    // 收藏接口
    addUserCollection() {
      let collection = {
        "userId": this.thisUserId,
        "videoId": this.video.id,
      }
      addUserCollection(collection).then((res) => {
        this.video.hasCollection = true;
      });
    },
    deleteUserCollection() {
      let collection = {
        "userId": this.thisUserId,
        "videoId": this.video.id,
      }
      deleteUserCollection(collection).then((res) => {
        this.video.hasCollection = false;
      });
    },


    loadComment() {
      this.request.get("/comment/getVideoComment/" + this.id).then(res => {
        this.comments = res.data;
        this.selectedTab = res.data.collectionName
        this.$forceUpdate(); // 强制更新组件
      });
    },
    // getCommentVideoDetail() {
    //   this.request.get(`/comment/findCommentVideoDetail/` + this.originId)
    //       .then(response => {
    //         this.commentList = response.data; // 将返回的评论详情列表赋值给commentList
    //       })
    //       .catch(error => {
    //         console.error('请求出错:', error);
    //       });
    // },
    toggleComments(item) {
      this.$set(item, 'showAllComments', !item.showAllComments);
    },
    // 发起评论
    saveComment() {
      if (!this.userInfo.id) {
        this.$message.warning("请登录后操作");
        return;
      }
      this.commentForm.videoId = this.id;
      if (this.commentForm.contentReply) {
        this.commentForm.content = this.commentForm.contentReply;
      }
      // 去除前后空格
      this.commentForm.content = this.commentForm.content.trim();

      if (this.commentForm.content == null || this.commentForm.content === "") {
        this.$message.error("请输入评论");
        return false;
      }

      this.request.post("/comment/save", this.commentForm).then(res => {
        if (res.code === '200') {
          this.$message.success("评论成功");
          this.commentForm = {};  // 初始化评论对象内容
          this.loadComment();
          this.dialogFormVisible = false;
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    deleteComment(id) {
      this.request.get("/comment/del" + id).then(res => {
        if (res.code === '200') {
          this.$message.success("删除成功")
          this.loadComment()
        } else {
          this.$message.error("删除失败")
        }
      })
    },
    // 进行回复
    handleReply(pid) {
      this.commentForm = { pid: pid }
      this.dialogFormVisible = true
    },

    /*上传时间*/
    formatTimeAgo(uploadDate) {
      const date = new Date(uploadDate);
      const now = new Date();
      const diffInMilliseconds = now - date;
      const diffInMinutes = Math.floor(diffInMilliseconds / (1000 * 60));

      if (diffInMinutes < 1) {
        return '刚刚';
      } else if (diffInMinutes < 60) {
        return diffInMinutes + '分钟前';
      } else {
        const diffInHours = Math.floor(diffInMilliseconds / (1000 * 60 * 60));

        if (diffInHours === 1) {
          return '1小时前';
        } else if (diffInHours < 24) {
          return diffInHours + '小时前';
        } else if (diffInHours < 48) {
          const hour = date.getHours();
          const minute = date.getMinutes();
          return '昨天 ' + hour + ':' + minute;
        } else if (diffInHours < 72) {
          return "2天前";
        } else {
          const year = date.getFullYear();
          const month = date.getMonth() + 1;
          const day = date.getDate();
          const hour = date.getHours();
          const minute = date.getMinutes();
          return year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
        }
      }
    },
  },
}
</script>

<style >
.main {
  min-width: 1000px;
  max-width: 1500px;
  margin: 0px auto;
  padding-left: 5%;
  padding-right: 5%;
}

.video-main {
  display: flex;
  width: 100%;
}

.video-info {
  width: 65%;
  min-width: 650px;
  height: 75px;
  margin-top: 20px;
}

.video-title {
  height: 35px;
  font-size: 20px;
  font-weight: 530;
  text-overflow: ellipsis;
}

.video-detail {
  margin-top: 5px;
}

.video-detail i {
  margin-right: 5px;
}

.video-detail span {
  margin-right: 20px;
}

.video-up {
  display: flex;
  justify-content: flex-start;
  width: 35%;
  min-width: 350px;
  height: 80px;
  margin-left: 20px;
  margin-top: 15px;
}

.up-cover {
  width: 70px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cover-img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  cursor: pointer;
}

.up-info {
  min-width: 250px;
  width: 70%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  font-family: SimHei, Arial, sans-serif;
}

.up-nickname span {
  color: #BE7E4A;
  cursor: pointer;
}

.up-introduction {
  margin-top: 6px;
  width: 100%;
  height: 20px
}

.up-introduction span {
  width: 100%;
  line-height: 20px;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 14px;
  color: #9c9fa4;
}

.up-concern {
  width: 100%;
  margin-top: 6px;
}

.up-concern .el-button {
  width: 100%;
  border-radius: 8px;
}

/* 视频区 */
.video-video {
  margin: 0px auto;
  width: 100%;
}

.demo {
  width: 65%;
  min-width: 680px;
  max-width: 900px;
  height: 35vw;
  min-height: 400px;
  max-height: 530px;
  margin-top: 15px;
}

.player {
  width: 100%;
  height: 100%;
}

.video-button {
  margin-top: 15px;
  margin-bottom: 5px;
}

.video-button i {
  margin-right: 5px;
  font-size: 20px;
}

.video-Introduction {
  margin-top: 10px;
}

/* 评论区 */
.video-comment {
  width: 65%;
  min-width: 680px;
  max-width: 900px;
}

.comment-top {
  width: 100%;
  margin-top: 20px;
}

.comment-top-count {
  padding-bottom: 10px;
  border-bottom: 1px solid orangered;
  font-size: 20px;
}

.comment-top-send {
  display: flex;
  align-items: center;
  margin-top: 20px;
}

.comment-top-cover {
  width: 50px;
  height: 50px;
  cursor: pointer;
  border-radius: 50%;
}

.comment-top-sendbutton {
  width: 80px;
  height: 54px;
  margin-left: 10px;
  font-size: 16px;
}




/*回复按钮*/
.comment-button :hover {
  color: #42b983;
}

/**/
.comment-a:hover {
  color: #F56C6C !important;
}

.hover-container:hover .comment-a {
  color: red;
}

.comment-content1 a {
  color: #4078c6 !important;
  cursor: pointer;
  font-family: SimHei, Arial, sans-serif;
  text-align: center;
  margin-left: 9px;
  font-size: 14px
}
</style>
